import 'package:flutter/foundation.dart';
import '../models/song.dart';
import '../services/audio_player_service.dart';
import '../services/music_scanner_service.dart';
import '../utils/image_cache_service.dart';

class MusicProvider with ChangeNotifier {
  final AudioPlayerService _audioService = AudioPlayerService();
  final MusicScannerService _scannerService = MusicScannerService();
  final ImageCacheService _imageCacheService = ImageCacheService();

  // 当前播放状态
  Song? _currentSong;
  List<Song> _playlist = [];
  PlayState _playState = PlayState.stopped;
  PlayMode _playMode = PlayMode.listLoop;
  Duration _currentPosition = Duration.zero;
  Duration _totalDuration = Duration.zero;
  
  // 音乐库数据
  List<Song> _allSongs = [];
  List<Song> _searchResults = [];
  bool _isLoading = false;
  String _errorMessage = '';

  // Getters
  Song? get currentSong => _currentSong;
  List<Song> get playlist => _playlist;
  PlayState get playState => _playState;
  PlayMode get playMode => _playMode;
  Duration get currentPosition => _currentPosition;
  Duration get totalDuration => _totalDuration;
  List<Song> get allSongs => _allSongs;
  List<Song> get searchResults => _searchResults;
  bool get isLoading => _isLoading;
  String get errorMessage => _errorMessage;
  
  // 播放状态计算属性
  bool get isPlaying => _playState == PlayState.playing;
  bool get isPaused => _playState == PlayState.paused;
  bool get isStopped => _playState == PlayState.stopped;
  bool get isLoadingMusic => _playState == PlayState.loading;
  bool get hasError => _playState == PlayState.error;
  
  // 进度相关计算属性
  double get progress {
    if (_totalDuration.inMilliseconds == 0) return 0.0;
    return _currentPosition.inMilliseconds / _totalDuration.inMilliseconds;
  }
  
  String get formattedPosition => _formatDuration(_currentPosition);
  String get formattedDuration => _formatDuration(_totalDuration);

  // Service getters
  AudioPlayerService get audioPlayerService => _audioService;
  MusicScannerService get musicScannerService => _scannerService;

  // 初始化
  Future<void> initialize() async {
    try {
      _setLoading(true);
      
      // 初始化音频服务
      await _audioService.initialize();
      
      // 监听音频服务状态变化
      _setupAudioServiceListeners();
      
      // 扫描本地音乐
      await loadMusicLibrary();
      
      _setLoading(false);
      print('MusicProvider: 初始化完成');
    } catch (e) {
      _setError('初始化失败: $e');
      print('MusicProvider: 初始化失败 - $e');
    }
  }

  // 设置音频服务监听器
  void _setupAudioServiceListeners() {
    // 监听当前歌曲变化
    _audioService.currentSongStream.listen((song) {
      _currentSong = song;
      notifyListeners();
    });

    // 监听播放状态变化
    _audioService.playStateStream.listen((state) {
      _playState = state;
      notifyListeners();
    });

    // 监听播放位置变化
    _audioService.positionStream.listen((position) {
      _currentPosition = position;
      notifyListeners();
    });

    // 监听总时长变化
    _audioService.durationStream.listen((duration) {
      _totalDuration = duration;
      notifyListeners();
    });

    // 监听播放模式变化
    _audioService.playModeStream.listen((mode) {
      _playMode = mode;
      notifyListeners();
    });
  }

  // 加载音乐库
  Future<void> loadMusicLibrary() async {
    try {
      _setLoading(true);
      _allSongs = await _scannerService.getAllMusicFiles();
      
      // 预加载所有专辑封面，提高显示性能
      for (final song in _allSongs) {
        _imageCacheService.preloadImage(song.albumArtUri);
      }
      
      _setLoading(false);
      print('MusicProvider: 加载了${_allSongs.length}首歌曲');
    } catch (e) {
      _setError('加载音乐库失败: $e');
    }
  }

  // 刷新音乐库
  Future<void> refreshMusicLibrary() async {
    await _scannerService.refreshMusicLibrary();
    await loadMusicLibrary();
  }

  // 播放歌曲
  Future<void> playSong(Song song, {List<Song>? playlist}) async {
    try {
      // 预加载专辑封面
      _imageCacheService.preloadImage(song.albumArtUri);
      
      // 如果提供了播放列表，设置为当前播放列表
      if (playlist != null) {
        setPlaylist(playlist);
      } else if (_playlist.isEmpty) {
        // 如果没有播放列表，使用全部歌曲作为播放列表
        setPlaylist(_allSongs);
      }

      await _audioService.playSong(song);
    } catch (e) {
      _setError('播放失败: $e');
    }
  }

  // 设置播放列表
  void setPlaylist(List<Song> songs, {int startIndex = 0}) {
    _playlist = songs;
    _audioService.setPlaylist(songs, startIndex: startIndex);
    notifyListeners();
  }

  // 播放/暂停切换
  Future<void> togglePlayPause() async {
    await _audioService.togglePlayPause();
  }

  // 上一首
  Future<void> previousSong() async {
    await _audioService.previousSong();
  }

  // 下一首
  Future<void> nextSong() async {
    await _audioService.nextSong();
  }

  // 跳转到指定位置
  Future<void> seekTo(Duration position) async {
    await _audioService.seek(position);
  }

  // 通过进度条设置播放位置
  Future<void> seekToProgress(double progress) async {
    if (_totalDuration.inMilliseconds > 0) {
      final position = Duration(
        milliseconds: (_totalDuration.inMilliseconds * progress).round(),
      );
      await seekTo(position);
    }
  }

  // 切换播放模式
  void togglePlayMode() {
    _audioService.togglePlayMode();
  }

  // 设置播放模式
  void setPlayMode(PlayMode mode) {
    _audioService.setPlayMode(mode);
  }

  // 设置音量
  Future<void> setVolume(double volume) async {
    await _audioService.setVolume(volume);
  }

  // 搜索歌曲
  Future<void> searchSongs(String query) async {
    try {
      _setLoading(true);
      _searchResults = await _scannerService.searchSongs(query);
      _setLoading(false);
    } catch (e) {
      _setError('搜索失败: $e');
    }
  }

  // 清空搜索结果
  void clearSearchResults() {
    _searchResults = [];
    notifyListeners();
  }

  // 获取随机歌曲
  Future<List<Song>> getRandomSongs(int count) async {
    return await _scannerService.getRandomSongs(count);
  }

  // 获取单首随机歌曲
  Future<Song?> getRandomSong() async {
    return await _scannerService.getRandomSong();
  }

  // 按专辑分组获取歌曲
  Future<Map<String, List<Song>>> getSongsByAlbum() async {
    return await _scannerService.getSongsByAlbum();
  }

  // 按艺术家分组获取歌曲
  Future<Map<String, List<Song>>> getSongsByArtist() async {
    return await _scannerService.getSongsByArtist();
  }

  // 获取播放模式图标
  String getPlayModeIcon() {
    return _audioService.getPlayModeIcon();
  }

  // 获取播放模式描述
  String getPlayModeDescription() {
    return _audioService.getPlayModeDescription();
  }

  // 工具方法：设置加载状态
  void _setLoading(bool loading) {
    _isLoading = loading;
    if (loading) {
      _errorMessage = '';
    }
    notifyListeners();
  }

  // 工具方法：设置错误信息
  void _setError(String error) {
    _isLoading = false;
    _errorMessage = error;
    notifyListeners();
  }

  // 工具方法：格式化时长
  String _formatDuration(Duration duration) {
    String twoDigits(int n) => n.toString().padLeft(2, '0');
    final minutes = twoDigits(duration.inMinutes.remainder(60));
    final seconds = twoDigits(duration.inSeconds.remainder(60));
    return '$minutes:$seconds';
  }

  // 清理资源
  @override
  void dispose() {
    _audioService.dispose();
    _scannerService.dispose();
    super.dispose();
  }
} 